package club.banyuan.reserve.service;

import club.banyuan.reserve.config.MyUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * @author HanChao
 * 描述信息：
 */
@Component("permissionService")
public class PermissionService {

    public boolean hasPermission (HttpServletRequest request, Authentication authentication) {

        Object principal = authentication.getPrincipal();
        //判断是否是认证的用户
        if (principal != null && principal instanceof MyUserDetails) {
            MyUserDetails user = (MyUserDetails) principal;
            //获取认证用户里的url列表
            Set<SimpleGrantedAuthority> authorities = (Set<SimpleGrantedAuthority>) user.getAuthorities();
            //判断url列表里是否包含request请求的url
            boolean contains = authorities.stream()
                    .map(SimpleGrantedAuthority::getAuthority)
                    .anyMatch(request.getRequestURI()::equals);
            return contains;
        }
        return false;

    }
}
